package jwt

import (
	"errors"
	"os"
	"strings"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

var (
	JWTSecretKey = []byte(os.Getenv("JWT_SECRET_KEY"))
)

type Claims struct {
	AdminId   int    `json:"admin_id"`
	AdminName string `json:"admin_name"`
	jwt.RegisteredClaims
}

// 生成jwt token
func GenerateJwtToken(adminId int, adminName string) (string, error) {
	// 定义过期时间
	expirationTime := time.Now().Add(24 * time.Hour)

	// 创建声明
	claims := &Claims{
		AdminId:   adminId,
		AdminName: adminName,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(expirationTime),
		},
	}
	// 创建 token
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	// 签名 token
	tokenString, err := token.SignedString(JWTSecretKey)
	if err != nil {
		return "", err
	}
	return tokenString, nil
}

// 验证并解析jwt token
func ParseJwtToken(tokenString string) (*Claims, error) {

	if tokenString == "" {
		return nil, errors.New("authorization header is missing")
	}
	// 移除 "Bearer " 前缀
	tokenString = strings.TrimPrefix(tokenString, "Bearer ")
	// 解析 token
	claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
		return JWTSecretKey, nil
	})

	if err != nil || !token.Valid {
		return nil, err
	}
	return claims, nil
}
